package com.club.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util
 */
public class DruidEncryptUtil {
    private static String publicKey;
    private static String privateKey;

    static {
        try {
            //生成密钥对,ConfigTools.genKeyPair(512)：生成 RSA 密钥对
            //参数 512：密钥长度（512位），建议使用更安全的 1024 或 2048 位
            //返回值：字符串数组，包含私钥和公钥
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0]; // 私钥（需要保密）
            System.out.println("privateKey:" + privateKey);
            publicKey = keyPair[1]; // 公钥（可以公开）
            System.out.println("publicKey:" + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    //私钥加密
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }
    //公钥解密
    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt:" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("123456");
        System.out.println("encrypt:" + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("decrypt"+ decrypt);
    }
}
